package com.jjwxc.jwjskandriod.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.config.BaseActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.LoginRequest;
import com.jjwxc.jwjskandriod.model.LoginResponse;
import com.jjwxc.jwjskandriod.model.VipDistanceResponse;
import com.jjwxc.jwjskandriod.readActivity.local.ReadSettingManager;
import com.jjwxc.jwjskandriod.readActivity.utils.SharedPreUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.StringUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.widget.LawDialog;
import com.umeng.analytics.MobclickAgent;
import com.zyq.easypermission.EasyPermission;
import com.zyq.easypermission.EasyPermissionResult;

import java.util.List;
import java.util.UUID;

public class SplashActivity extends BaseActivity {

    private ImageView img_start;

    @Override
    public int getContentViewId() {
        return R.layout.activity_splash;
    }

    @Override
    public void findView() {
        setNoTitle();
        img_start = findViewById(R.id.img_start);
        MobclickAgent.onEvent(this, UMConstant.LaunchesFirst);
    }


    @Override
    public void setListener() {
        img_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PreUtils.setBoolean("tourist", true);
                //游客登录
                touristLogin();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void afterCreate() {
        MobclickAgent.onEvent(this, UMConstant.NEW_CLIENT_OPEN);
        if (!PreUtils.getBoolean("XIE_YI", false)) {
            new LawDialog(SplashActivity.this, new LawDialog.DialogClickListener() {
                @Override
                public void onOkClick(Dialog dialog) {
                    PreUtils.setBoolean("XIE_YI", true);
                    mEasyPermission();
                }

                @Override
                public void onNoClick(Dialog dialog) {
                    finish();
                }
            }).show();
        } else {
            mEasyPermission();
        }

    }

    private int time = 0;

    //验证权限
    public void mEasyPermission() {
        EasyPermission.build()
                .mContext(SplashActivity.this)
                .mPerms(Manifest.permission.READ_PHONE_STATE)
                .mResult(new EasyPermissionResult() {
                    @Override
                    public void onPermissionsAccess(int requestCode) {
                        super.onPermissionsAccess(requestCode);
                        setAlphaAnimation();
                    }

                    @Override
                    public void onPermissionsDismiss(int requestCode, List<String> permissions) {
                        if (time >= 3) {
                            finish();
                            System.exit(0);
                        }

                        super.onPermissionsDismiss(requestCode, permissions);
                        time++;

                        showToast("请到设置的应用权限，开启权限，才能使用！");
                        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivityForResult(intent, 1024);

                    }
                }).requestPermission();
    }

    public void setAlphaAnimation() {
        new CountDownTimer(1000 * 2, 100) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                //如果说不是游客模式，切token为空
                if (PreUtils.getBoolean("tourist", true) || TextUtils.isEmpty(PreUtils.getString("token", ""))) {
//                    img_start.setVisibility(View.VISIBLE);

                    //遊客登錄
                    touristLogin();
                } else {
//                    img_start.setVisibility(View.GONE);
                    //登录
                    login();
                    MobclickAgent.onEvent(SplashActivity.this, UMConstant.LaunchesUnfirst);
                }


            }
        }.start();
    }

    public void login() {
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setDeviceId(getIMEI());
        loginRequest.setDeviceName(android.os.Build.MODEL);
        loginRequest.setLoginType("refresh_token");
        loginRequest.setRefreshToken(PreUtils.getString("RefreshToken", null));
        post(Url.login, "", LoginResponse.class, new FFNetWorkCallBack<LoginResponse>() {
            @Override
            public void onSuccess(LoginResponse response) {
                if (response.getCode() == 200) {
                    PreUtils.setBoolean("tourist", false);

                    PreUtils.setString("token", response.getData().getToken());
                    PreUtils.setString("Authorization", response.getData().getTokenHead() + response.getData().getToken());
                    PreUtils.setString("RefreshToken", response.getData().getRefreshToken());

                    Intent intent = new Intent();

                    if (PreUtils.getBoolean("QING_switch", false)) { //跳转到青少年模式
                        removeAllActivity();
                        intent = new Intent(SplashActivity.this, AdolescentBookActivity.class);
                        startActivity(intent);
                        MobclickAgent.onEvent(SplashActivity.this, UMConstant.YOUNG_TYPE_ANDROID_CLICK);
                    } else {
                        intent.setClass(SplashActivity.this, MainActivity.class);
                        startActivity(intent);
                        //获取VIP状态
                        getvipDistance();
                        finish();
                    }
                }

            }

            @Override
            public boolean onFail(LoginResponse response) {
                Intent intent = new Intent();
                intent.setClass(SplashActivity.this,
                        LoginActivity.class);
                startActivity(intent);
                finish();
                return false;
            }
        }, JSON.toJSONString(loginRequest));
    }

    public void touristLogin() {
        post(Url.login, "", LoginResponse.class, new FFNetWorkCallBack<LoginResponse>() {
            @Override
            public void onSuccess(LoginResponse response) {
                if (response.getCode() == 200) {
                    PreUtils.setBoolean("tourist", true);

                    //游客模式下背景图
                    PreUtils.setInt("head_bg", 3);
                    PreUtils.setInt("app_bg", 3);
                    int readbg = SharedPreUtils.getInstance().getInt(ReadSettingManager.SHARED_READ_BG, 0);
                    if (readbg < 3) {
                        SharedPreUtils.getInstance().putInt(ReadSettingManager.SHARED_READ_BG, 3);
                    }
                    //游客模式下用户信息
                    PreUtils.setString("token", response.getData().getToken());
                    PreUtils.setString("Authorization", response.getData().getTokenHead() + response.getData().getToken());
                    PreUtils.setString("RefreshToken", response.getData().getRefreshToken());
                    //正常模式下
                    Intent intent = new Intent();
                    intent.setClass(SplashActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                }

            }

            @Override
            public boolean onFail(LoginResponse response) {
                Intent intent = new Intent();
                intent.setClass(SplashActivity.this,
                        LoginActivity.class);
                startActivity(intent);
                finish();
                return false;
            }
        }, "{\"loginType\":\"tourist_mode\",\"deviceId\":\"" + getIMEI() + "\",\"deviceName\":\"" + android.os.Build.MODEL + "\"}");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1024) {
            afterCreate();
        }

    }

    public void getvipDistance() {
        int readbg = SharedPreUtils.getInstance().getInt(ReadSettingManager.SHARED_READ_BG, 0);
        //获取是否是VIP
        new FFNetWork().post(Url.vipDistance, null, new FFNetWorkCallBack<VipDistanceResponse>() {
            @Override
            public void onSuccess(VipDistanceResponse response) {
                if (response.getCode() == 200) {
                    //不是VIP
                    if (response.getData() > 0) {
                        PreUtils.setInt("head_bg", 3);
                        PreUtils.setInt("app_bg", 3);
                        if (readbg >= 0 && readbg < 3) {
                            SharedPreUtils.getInstance().putInt(ReadSettingManager.SHARED_READ_BG, 3);
                        }
                    } else {
                        PreUtils.setInt("head_bg", 0);
                        PreUtils.setInt("app_bg", 0);
                        if (readbg > 3) {
                            SharedPreUtils.getInstance().putInt(ReadSettingManager.SHARED_READ_BG, 0);
                        }
                    }


                }
            }

            @Override
            public boolean onFail(VipDistanceResponse response) {
                return false;
            }
        }, VipDistanceResponse.class);

    }

    @SuppressLint("HardwareIds")
    public String getIMEI() {
        String id;
        //android.telephony.TelephonyManager
        if (Build.VERSION.SDK_INT > 28) {
            id = getUniqueID();
            return id;
        }

        TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (mTelephony.getDeviceId() != null) {
            id = mTelephony.getDeviceId();
        } else {
            //android.provider.Settings;
            id = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        return id;
    }

    private String getUniqueID() {
        String id = null;
        String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!StringUtils.isEmpty(androidId) && !androidId.equals("9774d56d682e549c")) {
            try {
                UUID uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf-8"));
                id = uuid.toString();
                return id;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (StringUtils.isEmpty(id)) {
            id = getUUID();
        }

        //使用硬件信息拼凑出来的15位号码
        return StringUtils.isEmpty(id) ? UUID.randomUUID().toString() : id;
    }

    private String getUUID() {
        String serial = null;
        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 +
                Build.BRAND.length() % 10 +
                Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 +
                Build.HOST.length() % 10 +
                Build.ID.length() % 10 +
                Build.MANUFACTURER.length() % 10 + Build.MODEL.length() % 10 +
                Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 +
                Build.TYPE.length() % 10 +
                Build.USER.length() % 10; //13 位

        if (Build.VERSION.SDK_INT <= 29) {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    serial = Build.getSerial();
                } else {
                    serial = Build.SERIAL;
                }
                return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
            } catch (Exception e) {
                e.printStackTrace();
                serial = "serial"; // 随便一个初始化
            }
        } else {
            serial = Build.UNKNOWN; // 随便一个初始化
        }
        return serial;
    }
}